package com.xhc.demo.service;

import com.xhc.demo.entity.AdminUser;
import com.xhc.demo.repository.AdminUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.UUID;

@Service
public class AdminService {
    private static final Logger logger = LoggerFactory.getLogger(AdminService.class);
    
    @Autowired
    private AdminUserRepository adminUserRepository;

    public AdminUser login(String username, String password) {
        AdminUser user = adminUserRepository.findByUsername(username).orElse(null);
        
        if (user == null) {
            logger.info("User not found: " + username);
            return null;
        }

        // 使用明文密码比较
        if (user.getPassword().equals(password)) {
            logger.info("Password matched for user: " + username);
            String token = UUID.randomUUID().toString();
            user.setToken(token);
            user.setTokenExpiry(LocalDateTime.now().plusDays(7));
            return adminUserRepository.save(user);
        }

        logger.info("Password not matched for user: " + username);
        return null;
    }

    public AdminUser validateToken(String token) {
        return adminUserRepository.findByToken(token)
                .filter(user -> user.getTokenExpiry().isAfter(LocalDateTime.now()))
                .orElse(null);
    }
}
